package Action;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import Beans.Branch;
import Beans.Card;
import Beans.Company;
import Beans.Courier;
import Beans.Express;
import Beans.HibernateSessionFactory;
import DAO.CardDao;
import DAO.CompanyDao;
import DAO.CourierDao;
import DAO.ExpressDao;
import DAO.QueryDAO;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class CourierAction extends ActionSupport {
	private List<Courier> couriers;
	private List<Express> expressBranchs;
	private List<Company> companies;
	private List<Branch> branchs;
	private List<Card> cards;

	CourierDao courierDao = new CourierDao();
	CompanyDao companyDao = new CompanyDao();
	ExpressDao expressBranchDao = new ExpressDao();
	CardDao cardDao = new CardDao();
	QueryDAO queryDAO = new QueryDAO();

	private Courier courier = new Courier();

	private int courierID;
	// private int cardID;
	private int company = 0;
	private int branch;
	private int expressId;
	private BigInteger phoneNum;
	private String courierRfid;
	private String name;
	private String sernum;
	private String flag;
	private String value;

	/**
	 * 检测参数是否重复
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkValue() throws Exception {
		couriers = courierDao.checkValue(flag, value);
		if (couriers.size() == 0) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("0");
			out.close();
		} else {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("1");
			out.close();
		}
		return null;
	}

	/**
	 * 返回rfid
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getRfid() throws Exception {
		cards = cardDao.getSernumCard(sernum);
		if (cards.size() == 1) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print(cards.get(0).getRfid());
			out.close();
		} else {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("1");
			out.close();
		}
		return null;
	}

	/**
	 * 获取快递员信息 BY ID
	 * 
	 * @return
	 */
	public String getCourierById() {
		courier = courierDao.getCourierById(courierID);
		String sernum = courier.getSernum();
//		if (sernum != null) {
//			Card card = cardDao.getSernumCard(sernum).get(0);
//			cardDao.change(card, 0);
//		}
		cards = cardDao.getAdminCard();
		return "success";
	}
	/**
	 * 根据快递员手机号码获取快递员
	 * @return
	 */
	public String getByCourierPhone() {
		couriers = courierDao.getByCourierPhone(phoneNum);
		if(couriers.size()>0){
			whriteOffTime();
		}
		return "list";
	}
	/**
	 * 根据rfid获取快递员列表
	 * @return
	 */
	public String getByCourierRfid() {
		couriers = courierDao.getByRfid(courierRfid);
		if(couriers.size()>0){
			whriteOffTime();
		}
		return "list";
	}
	/**
	 * 根据快递员姓名获取快递员列表
	 * @return
	 */
	public String getByCourierName() {
		couriers = courierDao.getByName(name);
		if(couriers.size()>0){
			whriteOffTime();
		}
		return "list";
	}
	/**
	 * 写入离线时间
	 */
	public void whriteOffTime(){
		String sql = "select package_store_time from package p where p.package_courier_id = ? order by package_store_time desc";
		String sql1 = "select count(*) from package p where p.package_courier_id = ?";
		long today = new Date().getTime();
		Object object = null;
		for(Courier c:couriers){
			object = queryDAO.queryUniques(sql, c.getCourierId());
			HibernateSessionFactory.closeSession();
			c.saveNum = (BigInteger) queryDAO.queryUniques(sql1, c.getCourierId());
			HibernateSessionFactory.closeSession();
			BigInteger zero = new BigInteger("0");
			if(c.saveNum.compareTo(zero)>0){
				c.setErrorRate(new BigDecimal(c.getErrorTimes()).divide(new BigDecimal(c.saveNum), 2,BigDecimal.ROUND_HALF_DOWN));
			}else{
				c.setErrorRate(new BigDecimal(0));
			}
			if(object==null){
				c.offLineTime = -1;
			}else{
				c.offLineTime = (int) ((today-((Timestamp)object).getTime()) / (3600 * 24 * 1000));
			}
			courierDao.edit(c);
		}
	}

	/**
	 * 获取快递员信息 BY ID(包裹列表)
	 * 
	 * @return
	 */
	public String getPackageCourier() {
		couriers = courierDao.getPackageCourier(courierID);
		if(couriers.size()>0){
			whriteOffTime();
		}
		return "success";
	}

	/**
	 * 编辑快递员
	 * 
	 * @return
	 */
	public String editCourier() {
		Courier c = courierDao.getCourierById(courierID);
		Express express = expressBranchDao.getExpressBranch(expressId);
		if (courier.getRfid() != null) {
			cards = cardDao.getByRfid(courier.getRfid());
			if (cards.size() != 0) {
				Card card = cards.get(0);
				courier.setSernum(card.getSernum());
				cardDao.change(card, 1);
			}
		}
		courier.setExpress(express);
		courier.setCompany(express.getCompany().getCompanyName());
		courier.setCourierId(courierID);
		courier.setStatus(c.getStatus());
		courier.setErrorRate(c.getErrorRate());
		courier.setErrorTimes(c.getErrorTimes());
		courierDao.edit(courier);
		return "success";
	}

	/**
	 * 删除快递员
	 * 
	 * @return
	 */
	public String deleteCourier() {
		courier = courierDao.getCourierById(courierID);
		// String sernum = courier.getSernum();
		// if (sernum != null) {
		// Card card = cardDao.getSernumCard(sernum).get(0);
		// cardDao.change(card, 0);
		// }
		courier.setStatus(1);
		courier.setRfid(null);
		courier.setSernum(null);
		courierDao.edit(courier);
		return "success";
	}
	
	public String signCourier() {
		courier = courierDao.getCourierById(courierID);
		courier.setStatus(Integer.parseInt(flag));
		courierDao.edit(courier);
		return "success";
	}

	/**
	 * 获取快递员的网点和公司
	 * 
	 * @return
	 */
	public String getBranchAndCompany() {
		cards = cardDao.getAdminCard();
		companies = companyDao.getAllcompany();
		if (company != 0) {
			expressBranchs = expressBranchDao.getCompanyExpressBranch(company);
			return "jsonSuccess";
		} else {
			return "success";
		}
	}

	public String getAllCourierOfpack() {
		cards = cardDao.getAdminCard();
		return "success";
	}

	/**
	 * 获取所有快递员
	 * 
	 * @return
	 */
	public String getAll() {
		couriers = courierDao.getAll();
		if(couriers.size()>0){
			whriteOffTime();
		}
		return "success";
	}

	/**
	 * 通过公司和快递网点查询快递员
	 * 
	 * @return
	 */
	public String searchCourier() {
		couriers = courierDao.searchCourier(expressId);
		if(couriers.size()>0){
			whriteOffTime();
		}
		return "success";
	}

	/**
	 * 新增快递员
	 * 
	 * @return
	 */
	public String register() {
		Express express = expressBranchDao.getExpressBranch(expressId);
		/*
		 * if(courier.getRfid()!=null){
		 * cards=cardDao.getByRfid(courier.getRfid()); if(cards.size()!=0){ Card
		 * card = cards.get(0); courier.setSernum(card.getSernum());
		 * //cardDao.change(card, 1); } }
		 */
		courier.setExpress(express);
		courier.setCompany(express.getCompany().getCompanyName());
		// if(courierDao.isCourierExit(courier.getRfid()).size()>0){
		// courier.setStatus(0);
		// courierDao.edit(courier);
		// }else{
		courier.setErrorTimes(new BigInteger("0"));
		courier.setErrorRate(new BigDecimal(0));
		courier.setStatus(0);
		courierDao.save(courier);
		// }
		if ("1".equals(courier.getRole())) {
			express.setCourier(courier);
			expressBranchDao.edit(express);
		}
		return "add";
	}

	public List<Courier> getCouriers() {
		return couriers;
	}

	public void setCouriers(List<Courier> couriers) {
		this.couriers = couriers;
	}

	public Courier getCourier() {
		return courier;
	}

	public void setCourier(Courier courier) {
		this.courier = courier;
	}

	public int getCompany() {
		return company;
	}

	public void setCompany(int company) {
		this.company = company;
	}

	public List<Company> getCompanies() {
		return companies;
	}

	public void setCompanies(List<Company> companies) {
		this.companies = companies;
	}

	public int getCourierID() {
		return courierID;
	}

	public void setCourierID(int courierID) {
		this.courierID = courierID;
	}

	public List<Express> getExpressBranchs() {
		return expressBranchs;
	}

	public void setExpressBranchs(List<Express> expressBranchs) {
		this.expressBranchs = expressBranchs;
	}

	public int getExpressId() {
		return expressId;
	}

	public void setExpressId(int expressId) {
		this.expressId = expressId;
	}

	public List<Branch> getBranchs() {
		return branchs;
	}

	public void setBranchs(List<Branch> branchs) {
		this.branchs = branchs;
	}

	public int getBranch() {
		return branch;
	}

	public void setBranch(int branch) {
		this.branch = branch;
	}

	public List<Card> getCards() {
		return cards;
	}

	public void setCards(List<Card> cards) {
		this.cards = cards;
	}

	public String getSernum() {
		return sernum;
	}

	public void setSernum(String sernum) {
		this.sernum = sernum;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public BigInteger getPhoneNum() {
		return phoneNum;
	}

	public void setPhoneNum(BigInteger phoneNum) {
		this.phoneNum = phoneNum;
	}

	public String getCourierRfid() {
		return courierRfid;
	}

	public void setCourierRfid(String courierRfid) {
		this.courierRfid = courierRfid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}
